import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403 Forbidden', hidden: true }
  },
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    redirect: '/sales/orders',
    meta: { requiresAuth: true },
    children: [
      // 销售订单模块
      {
        path: '/sales',
        name: 'Sales',
        redirect: '/sales/orders',
        meta: { title: '销售订单', permission: 'sales' },
        children: [
          {
            path: 'orders',
            name: 'Orders',
            component: () => import('@/views/orders/OrderList.vue'),
            meta: { title: '订单明细记录', permission: 'sales:orders' }
          },
          {
            path: 'customers',
            name: 'Customers',
            component: () => import('@/views/customers/CustomerList.vue'),
            meta: { title: '客户信息维护', permission: 'sales:customers' }
          },
          {
            path: 'products',
            name: 'Products',
            component: () => import('@/views/products/ProductList.vue'),
            meta: { title: '产品信息维护', permission: 'sales:products' }
          },
          {
            path: 'expirations',
            name: 'Expirations',
            component: () => import('@/views/expirations/ExpirationList.vue'),
            meta: { title: '产品授权到期表', permission: 'sales:expirations' }
          },
          {
            path: 'server-rental',
            name: 'ServerRental',
            component: () => import('@/views/server-rental/ServerRentalList.vue'),
            meta: { title: '主机出租' }
          },
          {
            path: 'commission-categories',
            name: 'CommissionCategories',
            component: () => import('@/views/commission-categories/CommissionCategoryList.vue'),
            meta: { title: '提成分类管理', permission: 'sales:commission-categories', requiresAdmin: true }
          }
        ]
      },
      // 考勤与薪资模块
      {
        path: '/attendance',
        name: 'Attendance',
        redirect: '/attendance/record',
        meta: { title: '考勤与薪资', permission: 'attendance' },
        children: [
          {
            path: 'record',
            name: 'WorkRecord',
            component: () => import('@/views/attendance/WorkRecordList.vue'),
            meta: { title: '工时填报', permission: 'attendance:record' }
          },
          {
            path: 'calendar',
            name: 'DutyCalendar',
            component: () => import('@/views/attendance/DutyCalendar.vue'),
            meta: { title: '值班日历', permission: 'attendance:calendar' }
          },
          {
            path: 'salary',
            name: 'SalarySummary',
            component: () => import('@/views/attendance/SalarySummary.vue'),
            meta: { title: '薪资汇总', permission: 'attendance:salary' }
          },
          {
            path: 'detail',
            name: 'WorkSalaryDetail',
            component: () => import('@/views/attendance/WorkSalaryDetail.vue'),
            meta: { title: '工时薪资明细', permission: 'attendance:detail' }
          },
          {
            path: 'commission',
            name: 'CommissionDetail',
            component: () => import('@/views/attendance/CommissionDetail.vue'),
            meta: { title: '激活提成明细', permission: 'attendance:commission' }
          }
        ]
      },
      // 销售管理模块
      {
        path: '/management',
        name: 'Management',
        redirect: '/management/employees',
        meta: { title: '销售管理', permission: 'management', requiresAdmin: true },
        children: [
          {
            path: 'employees',
            name: 'Employees',
            component: () => import('@/views/management/EmployeeManagement.vue'),
            meta: { title: '员工管理', permission: 'sales:employees', requiresAdmin: true }
          },

          {
            path: 'dashboard',
            name: 'SalesDashboard',
            component: () => import('@/views/management/SalesDashboard.vue'),
            meta: { title: '销售情况', permission: 'sales', requiresAdmin: false }
          }
        ]
      },
      // 404页面
      {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404', hidden: true }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - NEWBE工作室` : 'NEWBE工作室订单管理系统';
  
  const userStore = useUserStore();
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin);
  
  // 如果是前往登录页，则直接放行
  if (to.path === '/login' || to.path === '/403') {
    next();
    return;
  }
  
  // 如果路由需要权限验证
  if (requiresAuth) {
    // 检查用户是否已登录
    if (!userStore.token) {
      console.log('未检测到token，重定向到登录页');
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }
    
    try {
      // 确保用户信息已加载
      if (!userStore.userInfo.id && userStore.token) {
        console.log('有token但没有用户信息，尝试获取用户数据');
        // 加载用户信息，捕获可能的错误
        try {
          await userStore.getUserData();
        } catch (error) {
          console.error('获取用户信息失败:', error);
          userStore.resetState();
          next({ path: '/login', query: { redirect: to.fullPath } });
          return;
        }
      }
      
      // 调试信息
      console.log('当前用户权限:', userStore.permissions);
      console.log('当前路由所需权限:', to.meta.permission);
      console.log('用户角色:', userStore.userInfo.role);
      
      // 检查是否需要管理员权限
      if (requiresAdmin && !userStore.isAdmin()) {
        console.log('需要管理员权限，但用户不是管理员');
        next({ path: '/403' });
        return;
      }
      
      // 检查是否有访问权限
      if (to.meta.permission && !userStore.hasPermission(to.meta.permission)) {
        console.log('用户没有所需权限:', to.meta.permission);
        
        // 特别处理：如果是访问首页或销售订单页面，尝试为用户添加权限
        if (to.path === '/' || to.path === '/sales/orders') {
          console.log('尝试为用户添加基本销售订单权限');
          // 临时添加权限
          if (!userStore.permissions.value.includes('sales')) {
            userStore.permissions.value.push('sales');
          }
          if (!userStore.permissions.value.includes('sales:orders')) {
            userStore.permissions.value.push('sales:orders');
          }
          next(); // 添加权限后放行
          return;
        }
        
        next({ path: '/403' });
        return;
      }
      
      next();
    } catch (error) {
      console.error('路由守卫错误:', error);
      next({ path: '/login' });
    }
  } else {
    next();
  }
});

export default router; 